package com.dotstone.chipism.activity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.DeviceType;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.MySocket;
import com.dotstone.chipism.bean.MySocket.RecDataCallBackListener_Lock;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.util.ConvertUtil;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class AddLockActivity extends BaseActivity {
	private LinearLayout mBackL;
	private TextView mStatusBar;
	private Button mRegisterB;
	private Button mCancelB;
	private Button mFinishB;
	private EditText mNameEd;
	private LinearLayout layout1;
	private LinearLayout layout2;
	private MySocket socket;
	private String cmd;
	private String mac;
	private SVProgressHUD mSVProgressHUD;
	private boolean finish = false;
	private int[] macInt = { 256, 256, 256, 256 }; // 定义一个数组 256是因为16进制转换不会出现256
													// 可以规避重复
	private int[] macRecInt = { 257, 257, 257, 257, 257 };// 定义从网关返回的指令解析出来的mac地址
															// 257是规避与macInt数组重复

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;
		case R.id.register_btn:
			registerLock();
			break;
		case R.id.cancel_btn:
			ToastShow.Show(getApplicationContext(), "取消添加门锁");
			// finish();
			break;
		case R.id.finish_btn:
			// 校验名字
			// 上传服务器
			String name = mNameEd.getText().toString();
			if (name.length() == 0 || name == null) {
				ToastShow.Show(getApplicationContext(),
						getString(R.string.namenonull));
				return;
			}
			if (name.length() < 2 || name.length() > 10) {
				ToastShow.Show(getApplicationContext(),
						getString(R.string.device_name_not_vaild));
				return;
			} else if (DeviceManager.getInstance().checkName(name)) {
				ToastShow.Show(getApplicationContext(),
						getString(R.string.device_name_exsits));
				return;
			}
			upload(name);
			break;
		default:
			break;
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				ToastShow.Show(getApplicationContext(), "注册失败");
				break;
			case 1:
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				layout2.setVisibility(View.VISIBLE);
				layout1.setVisibility(View.GONE);
				break;
			default:
				break;
			}
		}
	};

	private void upload(String name) {
		mSVProgressHUD = new SVProgressHUD(AddLockActivity.this);
		mSVProgressHUD.showWithStatus("正在保存");
		// 上传设备
		RequestParams params = new RequestParams(HttpURL.UPLOAD_DEVICE_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {

			obj.put("classification", "5");
			obj.put("key", "10000");
			obj.put("deviceAddress", (mac + 29).toUpperCase());
			obj.put("deviceModel", mac + 29);
			obj.put("deviceName", name);
			// obj.put("deviceType", type + "");
			obj.put("deviceType", DeviceType.DEVICE_TYPE_LOCK); // 用26去存
			obj.put("deviceVersion", "3.1.0");
			obj.put("deviceWifiSSID", mac + 29);
			obj.put("deviceId", "0");
			obj.put("productId", "5");
			obj.put("mainDeviceId", DeviceManager.getInstance().getmWlanId());
			obj.put("hid", DeviceManager.getInstance().hid);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token",
					(String) SPUtils.get(getApplicationContext(), "token", ""));
			Log.d("test", " upload obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("test", "upload=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					String value = jsonObject.getString("resultCode");
					if (value.equals("1")) {
						// String deviceId = jsonObject.getString("data");
						// 获取deviceId之后 上传所有按键
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						ToastShow.Show(getApplicationContext(), "保存成功！");
						finish();
					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(getApplicationContext(), "保存失败："
								+ errorMsg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void registerLock() {
		// TODO Auto-generated method stub
		// 显示进度框
		// 向服务器请求校验码
		// 获取校验码后跳转
		finish = false;
		mSVProgressHUD = new SVProgressHUD(AddLockActivity.this);
		mSVProgressHUD.showWithStatus("正在注册");
		getMac();
		// 检查超时
		checkTimeout();
	}

	private void getMac() {
		RequestParams params = new RequestParams(HttpURL.GET_LOCK_MAC);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token",
					(String) SPUtils.get(getApplicationContext(), "token", ""));
			Log.d("test", " upload obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("test", "upload=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					String value = jsonObject.getString("resultCode");
					if (value.equals("1")) {
						mac = jsonObject.getString("data");
						getLock();
					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(getApplicationContext(), "获取失败："
								+ errorMsg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void checkTimeout() {
		// 10秒超时
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					Thread.sleep(10* 1000);
					if (finish) {

					} else {
						Message msg = Message.obtain();
						msg.what = 0;
						mHandler.sendMessage(msg);
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}

	private void getLock() {
		// 拼接获取门锁指令
		// socket发送
		// 接收回调
		// 如果成功
		// 切换layout1和layout2
		cmd = getCmd(mac);
		socket.sendMqttData(cmd);
	}

	private void setRecall() {
		// TODO Auto-generated method stub
		socket.setRecDataCallBackListener_Lock(new RecDataCallBackListener_Lock() {

			@Override
			public void onReceiveData(String data) {
				// TODO Auto-generated method stub
				// 解析
				// 获取cmd
				// 如果符合 再该
				int macRecInt[] = parseData(data);
				Log.i("wmy", "获取数据" + " " + macRecInt[0] + " " + data);
				if (macRecInt[0] == 177 && macRecInt[1] == macInt[0]
						&& macRecInt[2] == macInt[1]
						&& macRecInt[3] == macInt[2]
						&& macRecInt[4] == macInt[3]) {
					finish = true;
					Message msg = Message.obtain();
					msg.what = 1;
					mHandler.sendMessage(msg);
				}
			}
		});
	}

	private int[] parseData(String data) {
		int macRecInt[] = new int[5];
		try {
			JSONObject jo = new JSONObject(data);
			String g = jo.getString("g");
			JSONObject jo1 = new JSONObject(g);
			JSONArray ja = jo1.getJSONArray("data");
			macRecInt[0] = ja.getInt(9);
			macRecInt[1] = ja.getInt(10);
			macRecInt[2] = ja.getInt(11);
			macRecInt[3] = ja.getInt(12);
			macRecInt[4] = ja.getInt(13);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return macRecInt;
	}

	private String getCmd(String mac) {
		String cmd = "";
		byte[] macByte = Util.hexStringToBytes(mac);
		macInt = Util.byte2HexStr(macByte);
		int[] getData = new int[] { 1, 17, 34, 51, 68, 41, 90, 126, 8, 34, 0,
				0, 0, 0, 0, 1, 0 };
		getData[10] = macInt[0];
		getData[11] = macInt[1];
		getData[12] = macInt[2];
		getData[13] = macInt[3];
		int n = 0;
		for (int i = 7; i < 16; i++) {
			n += getData[i];
		}
		getData[16] = n % 256;
		// getData[16] = 18;
		cmd = ConvertUtil.convertGetLockCmd(getData);
		return cmd;
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_add_lock;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mBackL = $(R.id.back_layout);
		mStatusBar = $(R.id.tv_statusBar_mian);
		layout1 = $(R.id.layout1);
		layout2 = $(R.id.layout2);
		mRegisterB = $(R.id.register_btn);
		mCancelB = $(R.id.cancel_btn);
		mFinishB = $(R.id.finish_btn);
		mNameEd = $(R.id.name_ed);
		boolVersion();
		mBackL.setOnClickListener(this);
		mRegisterB.setOnClickListener(this);
		mCancelB.setOnClickListener(this);
		mFinishB.setOnClickListener(this);
		socket = SocketManager.getInstance().sMap.get(DeviceManager
				.getInstance().getmWlanId());
		if(!socket.isLocalSuccess()){
			ToastShow.Show(getApplicationContext(), "只有本地连接的网关才能添加门锁");
			finish();
		}
		setRecall();
		mNameEd.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					mNameEd.setHint("");
				} else {
					if (mNameEd.getText().toString().length() == 0) {
						mNameEd.setHint(getString(R.string.name_device));
					}
				}
			}
		});
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
//			getWindow().addFlags(
//					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar
					.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

}
